package cn.walls1717.wallsmall.product.exception;

import cn.walls1717.wallsmall.common.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

import static cn.walls1717.wallsmall.common.exception.BizCodeEnum.UNKNOWN_EXCEPTION;
import static cn.walls1717.wallsmall.common.exception.BizCodeEnum.VALID_EXCEPTION;

/**
 * 全局异常处理
 *
 * @author walls1717
 * @since 2022/10/24 11:21
 **/
@RestControllerAdvice(basePackages = "cn.walls1717.wallsmall.product.controller")
public class GlobalExceptionControllerAdvice {

    /**
     * 参数校验错误处理
     *
     * @param validException 参数校验异常
     * @return 统一异常处理结果
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException validException) {
        BindingResult bindingResult = validException.getBindingResult();
        HashMap<String, String> errorMap = new HashMap<>(15);
        // 将异常字段与异常信息添加到map中，统一返回
        bindingResult.getFieldErrors().forEach(error -> {
            String message = error.getDefaultMessage();
            String field = error.getField();
            errorMap.put(field, message);
        });
        return R.error(VALID_EXCEPTION.getCode(), VALID_EXCEPTION.getMsg()).put("data", errorMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        throwable.printStackTrace();
        return R.error(UNKNOWN_EXCEPTION.getCode(), UNKNOWN_EXCEPTION.getMsg());
    }
}
